/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jlibrarian.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jlibrarian.BookManagerImpl;
import jlibrarian.DbManager;
import jlibrarian.entities.Book;
import jlibrarian.interfaces.BookManager;

/**
 *
 * @author dandelion8
 */
public class CreateBookServlet extends HttpServlet {

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // initialize
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();

        // glue in errors
        final String glue = ", ";



        Map<String, String> params = new TreeMap<String, String>();
        params.put("title", "název");
        params.put("authors", "autor");
        params.put("quantity", "počet výtisků");
        params.put("note", "poznámka");


        // errors
        StringBuilder errorCache = new StringBuilder();

        // add values
        Map<String, String> values = new HashMap<String, String>();
        for (Entry<String, String> p : params.entrySet()) {
            String value = request.getParameter(p.getKey());
            if (value == null || value.length() == 0) {
                errorCache.append(p.getValue()).append(glue);
            }
            values.put(p.getKey(), value);
        }


        // mh    saves messages to session
        MessagesHandler mh = new MessagesHandler(session);


        boolean error = false;


        //validate quantity
        int quantity = -1;
        try {
            quantity = Integer.parseInt(values.get("quantity"));
            if (quantity < 0) {
                mh.setMessage("error", "Není možné zadávat záporný počet knih");
                error = true;
            }
        } catch (NumberFormatException nfe) {
            mh.setMessage("error", "Počet knih musí být číslo.");
            error = true;
        }



        // set error message
        if (errorCache.length() > 0) {
            // set error
            mh.setMessage("error", "Nutné vyplnit položky: " + errorCache.substring(0, errorCache.length() - glue.length()) + ".");
            error = true;
        }

        if (error) {
            // store values
            session.setAttribute("book-values", values);
            // redirecting back
            response.sendRedirect(request.getContextPath() + "/book-create.jsp");
            return;
        }
        // delete values
        session.setAttribute("book-values", null);

        // OK
        //write book was created only if there is no error
        if (!error) {
            mh.setMessage("status", "Kniha byla vytvořena.");
        }

        // creating
        Book book = new Book();
        book.setTitle(values.get("title"));
        book.setAuthors(values.get("authors"));
        book.setQuantity(quantity);
        book.setNote(values.get("note"));

        BookManager bm = new BookManagerImpl(DbManager.getDataSource());
        bm.createBook(book);

        response.sendRedirect(request.getContextPath() + "/book-list.jsp");

    }
}
